package com.jzg.jcptadmin.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.ACache;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.MainPresenter;
import com.jzg.jcptadmin.presenter.StatusPresenter;
import com.jzg.jcptadmin.viewinterface.MainActivityInterface;
import com.jzg.jcptadmin.viewinterface.StatusInterface;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class SplashActivity extends BaseActivity implements MainActivityInterface, StatusInterface {

    private MainPresenter mainPresenter;
    private StatusPresenter statusPresenter;
    private SharedPreferences userInfo;
    private String name;
    private String pass;
    private String jpushId;
    private String loginTag;
    private String error;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        supportRequestWindowFeature(Window.FEATURE_PROGRESS);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {   //解决某些系统(oppo)点击home键再打开就重新启动app
            finish();
            return;
        }


        isAutoLogin();

        Observable.timer(3000, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()).
                subscribe(new Action1<Long>() {
            @Override
            public void call(Long aLong) {
//                appContext.initImageLoader();
                // 添加内存泄漏监听
//        refWatcher = LeakCanary.install(this);
                // 初始化CustomActivityOnCrash
//                appContext.CustomActivityOnCrashInit();
                //初始化网络框架
//                appContext.initHttp();
//                appContext.initCityHttp();
//                appContext.initGlobalHttp();
                //  initFile();
                //初始化网络连接监听
//                appContext.initNet();
//                JPushInterface.setDebugMode(false);    // 设置开启日志,发布时请关闭日志
//                JPushInterface.init(appContext);            // 初始化 JPush
                if ("suc".equals(loginTag)){
                    MyToast.showShort("成功登录");
                    //跳转到首页
                    ActivityHelp.startActivity(SplashActivity.this, HomeActivity.class);
                }else if ("fail".equals(loginTag) || TextUtils.isEmpty(loginTag)){
                    if (!TextUtils.isEmpty(error)){
                        MyToast.showShort(error);
                    }
                    ActivityHelp.startActivity(SplashActivity.this, MainActivity.class);
                }

                finish();
            }
        });

    }

    private void isAutoLogin() {
        jpushId = JPushInterface.getRegistrationID(appContext);

        mainPresenter = new MainPresenter(DataManager.getInstance());
        mainPresenter.attachView(this);

        statusPresenter = new StatusPresenter(DataManager.getInstance(),appContext);
        statusPresenter.attachView(this);

        statusPresenter.LoadStatusData();
        userInfo = getSharedPreferences("user_info", 0);
        name = userInfo.getString("name", "");
        pass = userInfo.getString("password", "");
        if(!TextUtils.isEmpty(name) && !TextUtils.isEmpty(pass)){
            mainPresenter.isLogout(true);
        }

    }

    @Override
    public void success(User user) {
        mainPresenter.savaUser(appContext, user);
        JPushInterface.resumePush(getApplicationContext());
        if ("0".equals(user.getJpushRegister())) {
            setJPushTag(user);
        } else {
        }
        loginTag = "suc";


    }

    @Override
    public void failed(String error) {
        this.error = error;
        loginTag = "fail";
        this.error = error;
        ACache.get(this).remove("User");
    }

    @Override
    public void autoLogin() {
        saveUsername(name, pass);
        showDialog();
        mainPresenter.login();
    }
    /**
     * 保存用户名、密码信息
     */
    private void saveUsername(String user, String pass) {
        userInfo.edit().putString("name", user).putString("password", pass).commit();
    }
    @Override
    public void exitLogin() {

    }

    @Override
    public Map<String, String> getLoginParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("lgcode", name);
        params.put("pwd", pass);
        params.put("op", "login");
        params.put("tokenid", "6");
        if (!TextUtils.isEmpty(jpushId)) {
            params.put("registrationId", jpushId);
        }
        Map<String, Object> signMap = new HashMap<>();
        signMap.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(signMap));
        return params;
    }

    @Override
    public Map<String, String> getLoadStatusParams() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("tokenid", "6");
        Map<String, Object> signMap = new HashMap<>();
        signMap.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(signMap));
        return params;
    }

    /**
     * 设置激光推送别名
     *
     * @param user
     */
    private void setJPushTag(final User user) {
        Set<String> tagSet = new HashSet<String>();
        tagSet.add(String.valueOf(user.getUserId()));//正式环境
        JPushInterface.setTags(getApplicationContext(), tagSet, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                if (i == 0) {  //成功
//                    finish();
                } else if (i == 6002) {
                    Observable.timer(10, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
                            //observeOn(): 指定 Subscriber 所运行在的线程。或者叫做事件消费的线程。下面的call方法会在io线程中执行
                            .observeOn(Schedulers.io())
                            //subscribeOn(): 指定 subscribe() 所发生的线程，即 Observable.OnSubscribe 被激活时所处的线程。或者叫做事件产生的线程。
                            .subscribeOn(Schedulers.io())
                            .subscribe(new Action1<Long>() {
                                @Override
                                public void call(Long s) {
                                    Set<String> tagSet = new HashSet<String>();
//                                    tagSet.add("test" + String.valueOf(user.getUserId()));//测试环境
                                    tagSet.add(String.valueOf(user.getUserId()));//正式环境
                                    JPushInterface.setTags(getApplicationContext(), tagSet, null);
                                }
                            });
                } else {
//                    MyToast.showShort("设置推送失败");
//                    finish();
                }

            }
        });
        JPushInterface.resumePush(getApplicationContext());
    }

}
